//
//  OAuthViewController.m
//  OC-LBWeibo
//
//  Created by 李博 on 15/6/28.
//  Copyright © 2015年 libo. All rights reserved.
//

#import "OAuthViewController.h"
#import "SVProgressHUD.h"
#import "NetworkTools.h"
#import "UserAccount.h"

#define WB_Client_ID @"31259537"
#define WB_Redirect_URI @"http://www.baidu.com"
#define WB_App_Secret @"7bac4cdb0d8f829d11d7e4f3c71b339c"

@interface OAuthViewController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView *webView;

@end

@implementation OAuthViewController




- (void)loadView
{
    self.webView = [[UIWebView alloc]init];
    self.webView.delegate = self;
    self.view = self.webView;
    
    self.title = @"新浪微博";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    
}

- (void)close
{
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // 加载授权页面
    [self loadOAuthView];
}

- (void)loadOAuthView
{
    NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",WB_Client_ID,WB_Redirect_URI];
    NSURL *url = [NSURL URLWithString:urlString];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    
}

- (BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = request.URL.absoluteString;
    NSLog(@"%@",urlString);
    
    if (![urlString hasPrefix:WB_Redirect_URI]) {
        NSLog(@"继续加载。。");
        return YES;
    }
    NSLog(@"需要判断。。");
    NSString *query = request.URL.query;
    NSString *codeStr = @"code=";
    
    if ([query hasPrefix:codeStr]) {
        NSString *code = [query substringFromIndex:codeStr.length];
        NSLog(@"授权码code=%@",code);
        
        [self loadAccessToken:code];
    }else{
        NSLog(@"取消授权。。");
        [self close];
    }
    return NO;
}

- (void)webViewDidStartLoad:(nonnull UIWebView *)webView
{
    [SVProgressHUD show];
}

- (void)webViewDidFinishLoad:(nonnull UIWebView *)webView
{
    [SVProgressHUD dismiss];
}

- (void)loadAccessToken:(NSString *)code
{
    NSString *urlString = @"oauth2/access_token";
    
    //请求参数
    NSDictionary *params = @{@"client_id":WB_Client_ID,@"client_secret":WB_App_Secret,@"grant_type":@"authorization_code",@"code":code,@"redirect_uri":WB_Redirect_URI};
    
    [[NetworkTools sharedNetworkTools] POST:urlString parameters:params success:^(NSURLSessionDataTask *task, id JSON) {
        NSLog(@"%@",JSON);
        //加载用户信息
        [[UserAccount userWithDict:JSON] loadUserInfo:^(UserAccount *account, NSError *error) {
            
            if (account != nil) {
                
                UserAccount *user = [UserAccount sharedUserAccount];
                user = account;
                //发送通知
                [[NSNotificationCenter defaultCenter]postNotificationName:LBSwitchRootVCNotification object:@(YES)];
                
                //关闭当前控制器
                [self close];
                return;
            }
            NSLog(@"%@",error);
            [SVProgressHUD showInfoWithStatus:@"你的网速不给力。"];
        }];
        

//                //2. 发送通知
//                NSNotificationCenter.defaultCenter().postNotificationName(LBSwitchRootVCNotification, object: false)

        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD showInfoWithStatus:@"网络不给力。。" ];
    }];
}

@end
